package com.yanxin.workflow.service.jaxrs.client;


import com.ibm.wsdl.PortTypeImpl;
import com.ibm.wsdl.xml.WSDLReaderImpl;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.stereotype.Service;

import javax.wsdl.Definition;
import javax.wsdl.Operation;
import javax.wsdl.WSDLException;
import javax.wsdl.xml.WSDLReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class WsInvokeClient {

    public Object[] send(String wsdl, String method, Object... params) {

        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(wsdl);
        // 需要密码的情况需要加上用户名和密码
        // client.getOutInterceptors().add(new ClientInterceptor("", ""));
        Object[] objects = new Object[0];
        try {
            // invoke("方法名",参数1,参数2,参数3....); 这里注意如果是复杂参数的话，要保证复杂参数可以序列化
            objects = client.invoke(method, params);
        } catch (Exception e) {
            // log.error("ws调用异常: {}", e.getMessage());
        }
        // log.info("返回数据: {}", objects);
        return objects;
    }

    public List<Operation> getPortTypeOperations(String wsdlUrl) {
        List<Operation> operationList = new ArrayList();
        try {
            WSDLReader reader = new WSDLReaderImpl();
            reader.setFeature("javax.wsdl.verbose", false);
            Definition definition = reader.readWSDL(wsdlUrl.toString());
            Map defMap = definition.getAllPortTypes();
            Collection<PortTypeImpl> collection = defMap.values();
            for (PortTypeImpl portType : collection) {
                operationList.addAll(portType.getOperations());
            }
        } catch (WSDLException e) {
            System.out.println("get wsdl operation fail.");
            e.printStackTrace();
        }
        return operationList;
    }
}
